﻿using System;
using System.Data.SqlTypes;
using System.Web;
using System.Web.Mvc;
using viBook.Common;
using viBook.Controllers;
using viBook.Models;
using viBook.Repositories;

namespace viBook.Filters
{
    public abstract class ExtendedAuthenticationBase : AuthorizeAttribute
    {
        #region Constructors and Repository vars

        private readonly IUserRepository _userRepository;

        protected ExtendedAuthenticationBase()
            : this(new UserRepository())
        {
        }

        protected ExtendedAuthenticationBase(IUserRepository userRepository)
        {
            _userRepository = userRepository;
        }

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            var isAuthorized = base.AuthorizeCore(httpContext);
            IsLoggedIn = isAuthorized;

            if (isAuthorized)
            {
                var request = httpContext.Request;
                var resourceName = string.IsNullOrEmpty(ResourceName) ? request.RequestContext.RouteData.Values["Controller"].ToString() : ResourceName;
                var resourceNameEnum = Helpers.Helpers.ControllerNameToEnum(resourceName.ToLower());
                var resourceIdVar = 0;
                if (request.RequestContext.RouteData.Values[ResourceId ?? "id"] != null)
                    try
                    {
                        resourceIdVar = int.Parse(request.RequestContext.RouteData.Values[ResourceId ?? "id"].ToString());
                    }
                    catch (Exception)
                    {
                        resourceIdVar = 0;
                    }
                var userId = ((ExtendedIdentity)httpContext.User.Identity).Id;
                if (resourceIdVar == 0 && resourceNameEnum != ControllerEnum.Admins) return true;

                if (SessionPersiter.User.IsExternal)
                    IsActivated = true;
                else
                    IsActivated = SessionPersiter.User.Status.Equals("Approved", StringComparison.OrdinalIgnoreCase);
                IsAllowToUseResource = _userRepository.CheckResourceAccessibility(userId, resourceNameEnum, resourceIdVar);
                return IsAllowToUseResource;
            }
            return isAuthorized;
        }
        #endregion

        protected bool IsActivated;
        protected bool IsAllowToUseResource;
        protected bool IsLoggedIn;
        public string ResourceName { get; set; }
        public string ResourceId { get; set; }
    }
}